package org.elucid.gadmin;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.elucid.gadmin.ui.GFrame;

import com.apple.eawt.AppEvent;
import com.apple.eawt.Application;
import com.apple.eawt.OpenFilesHandler;
import com.google.gson.Gson;

/**
 * 
 * @author george
 *
 */
@SuppressWarnings("restriction")
public class Main implements OpenFilesHandler{

	private static final Logger log = Logger.getLogger(Main.class);
	
	private static final String SETTINGS_JSON = "settings.json";
	public static Settings settings = null;
	static Gson gson = null;
	private static GFrame view;
	
	private List<File> files = new ArrayList<File>();

	/**
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {

		Main main = new Main();
		for(String arg : args)
		{
			File file = new File(arg);
			main.files.add(file);
		}
		
		main.init(args);
	}
	
	/**
	 * 
	 * @param args
	 * @throws Exception
	 */
	public void init(String[] args) throws Exception
	{
		log.info(String.format("init() args: %s", args.length));
		for( String arg : args )
		{
			log.info(String.format("arg %s", arg));
		}
			
		gson = new Gson();
		
		loadSettings();
		
		view = new GFrame(settings);
		
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
            	
            	view.setVisible(true);
            	
            }
        });
	}
	
	
	public Main() {
        Application.getApplication().setOpenFileHandler(this);
    }

    public List<File> getFiles() {
        return files;
    }

    public void openFiles(AppEvent.OpenFilesEvent event) {
    	
    	files = event.getFiles();
    	for( File file : files )
    	{
    		log.info( String.format("openFiles, openFile: %s ", file.getAbsolutePath() ));
    	}
    	
    	// wait for UI to be initialised
    	while( view == null  )
    	{
    		Thread.yield();
    	}
    	
    	view.openFiles( files );
    }
    

	/**
	 * 
	 * @throws FileNotFoundException
	 */
	private static void loadSettings() throws FileNotFoundException {
		BufferedReader br = new BufferedReader(new FileReader(SETTINGS_JSON));

		// convert the json string back to object
		settings = gson.fromJson(br, Settings.class);
		
	}
    
	/**
	 * 
	 * @throws Exception
	 */
	@SuppressWarnings("unused")
	private static void saveSettings() throws Exception {
		String json = gson.toJson(settings);

		// write converted json data to a file named "file.json"
		FileWriter writer = new FileWriter(SETTINGS_JSON);
		writer.write(json);
		writer.close();
	}
	
}
